<?php

/**
 * 编辑器配置
 * File Name：AttachmentController.php
 * File Encoding：UTF-8
 * File New Time：2014-10-15 10:15:31
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class AttachmentController extends YzwController {

    //编辑器初始配置
    private $confing = array(
        /* 上传图片配置项 */
        'imageActionName' => 'uploadimage',
        'imageFieldName' => 'upfilesss',
        'imageMaxSize' => 20971520, /* 上传大小限制，单位B */
        'imageAllowFiles' => array('.png', '.jpg', '.jpeg', '.gif', '.bmp'),
        'imageCompressEnable' => true,
        'imageCompressBorder' => 1600,
        'imageInsertAlign' => 'none',
        'imageUrlPrefix' => '',
        'imagePathFormat' => '',
        /* 涂鸦图片上传配置项 */
        'scrawlActionName' => 'uploadscrawl',
        'scrawlFieldName' => 'upfile',
        'scrawlPathFormat' => '',
        'scrawlMaxSize' => 0,
        'scrawlUrlPrefix' => '',
        'scrawlInsertAlign' => 'none',
        /* 截图工具上传 */
        'snapscreenActionName' => 'uploadimage',
        'snapscreenPathFormat' => '',
        'snapscreenUrlPrefix' => '',
        'snapscreenInsertAlign' => 'none',
        /* 抓取远程图片配置 */
        'catcherLocalDomain' => array('127.0.0.1', 'localhost', 'img.baidu.com'),
        'catcherActionName' => 'catchimage',
        'catcherFieldName' => 'source',
        'catcherPathFormat' => '',
        'catcherUrlPrefix' => '',
        'catcherMaxSize' => 20971520,
        'catcherAllowFiles' => array('.png', '.jpg', '.jpeg', '.gif', '.bmp'),
        /* 上传视频配置 */
        'videoActionName' => 'uploadvideo',
        'videoFieldName' => 'upfile',
        'videoPathFormat' => '',
        'videoUrlPrefix' => '',
        'videoMaxSize' => 20971520,
        'videoAllowFiles' => array(".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg", ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"),
        /* 上传文件配置 */
        'fileActionName' => 'uploadfile',
        'fileFieldName' => 'upfile',
        'filePathFormat' => '',
        'fileUrlPrefix' => '',
        'fileMaxSize' => 20971520,
        'fileAllowFiles' => array('.png', '.jpg', '.jpeg', '.gif', '.bmp', ".flv", ".swf", 'zip', 'rar', '7z'),
        /* 列出指定目录下的图片 */
        'imageManagerActionName' => 'listimage',
        'imageManagerListPath' => '',
        'imageManagerListSize' => 20,
        'imageManagerUrlPrefix' => '',
        'imageManagerInsertAlign' => 'none',
        'imageManagerAllowFiles' => array('.png', '.jpg', '.jpeg', '.gif', '.bmp'),
        /* 列出指定目录下的文件 */
        'fileManagerActionName' => 'listfile',
        'fileManagerListPath' => '',
        'fileManagerUrlPrefix' => '',
        'fileManagerListSize' => '',
        'fileManagerAllowFiles' => array(".flv", ".swf",),
    );
    private $isadmin = 0;
    private $uid = 0;

    //初始化
    public function init() {
        if (Yii::app()->request->isPostRequest) {
            $authkey = Yii::app()->request->getParam('authkey');
            $sess_id = Yii::app()->request->getParam('sessid');
            $userid = Yii::app()->request->getParam('uid');
            $this->isadmin = (int) Yii::app()->request->getParam('isadmin');
            $key = md5(Yii::app()->params['authcode'] . $sess_id . $userid . $this->isadmin);
            if ($key != $authkey) {
                exit(json_encode(array('state' => '身份认证失败！')));
            } else {
                $this->uid = $userid;
            }
        }
        parent::init();
    }

    //配置
    public function actionConfig() {
        $action = Yii::app()->request->getParam('action');
        $result = array();
        switch ($action) {
            case 'config':
                $result = $this->confing;
                break;
            //上传涂鸦
            case 'uploadscrawl':
                $base64Data = $_POST[$this->confing['scrawlFieldName']];
                if (empty($base64Data)) {
                    exit(json_encode(array('state' => '没有涂鸦内容！')));
                }
                $img = base64_decode($base64Data);
                $oriName = 'scrawl.png';
                $fileType = 'png';
                $fileSize = strlen($img);
                //上传目录
                $savePath = AttachmentModel::model()->getFilePath();
                //保存文件名
                $fileName = UploadFile::getInstance()->getSaveName(array('name' => $oriName, 'extension' => 'png'));
                //保存地址
                $filePath = $savePath . $fileName;
                //临时路径
                $tmp = Yii::app()->basePath . $fileName;
                //保存后的访问地址
                $url = ConfigModel::model()->getConfig('sitefileurl') . $filePath;
                //写入临时文件
                if (file_put_contents($tmp, $img)) {
                    require_once Yii::app()->basePath . '/extensions/Oss/sdk.class.php';
                    //oss上传
                    $oss_sdk_service = new ALIOSS();
                    $oss_sdk_service->set_debug_mode(true);
                    $options = array(
                        ALIOSS::OSS_CONTENT_TYPE => MimeTypes::get_mimetype($fileType),
                        ALIOSS::OSS_CONTENT_LENGTH => $fileSize,
                    );
                    $return = $oss_sdk_service->upload_file_by_file(UploadFile::getInstance()->bucket, $filePath, $tmp, $options);
                    @unlink($tmp);
                    if (empty($return->header['_info']['url']) || !isset($return->header['_info']['url'])) {
                        exit(json_encode(array('state' => '保存失败！')));
                    }
                    $file = array(
                        'name' => $oriName,
                        'savepath' => $savePath,
                        'savename' => $fileName,
                        'size' => $fileSize,
                        'extension' => $fileType,
                    );
                    AttachmentModel::model()->record($file, UploadFile::getInstance()->oss);
                    $result = array(
                        'state' => 'SUCCESS', //成功返回标准，否则是错误提示
                        'url' => $url, //成功地址
                        'title' => $oriName, //上传后的文件名
                        'original' => $oriName, //原来的
                    );
                } else {
                    exit(json_encode(array('state' => '保存失败！')));
                }
                break;
            //上传图片
            case 'uploadimage':
                $Attachment = UploadFile::getInstance();
                //设置上传类型，强制为图片类型
                $Attachment->allowExts = array("jpg", "png", "gif", "jpeg");
                //开始上传
                $status = $Attachment->upload();
                if ($status) {
                    $info = $Attachment->getUploadFileInfo();
                    $url = ConfigModel::model()->getConfig('sitefileurl') . $info[0]['savepath'] . $info[0]['savename'];
                    // 设置附件cookie
                    AttachmentModel::model()->upload_json($info[0]['aid'], $url, str_replace(array("\\", "/"), "", $info[0]['name']));
                    $result = array(
                        'state' => 'SUCCESS', //成功返回标准，否则是错误提示
                        'url' => $url, //成功地址
                        'title' => str_replace(array("\\", "/"), "", $info[0]['savename']), //上传后的文件名
                        'original' => $info[0]['tmp_name'], //原来的
                    );
                } else {
                    $result = array(
                        'state' => $Attachment->getError()? : '上传失败'
                    );
                }
                break;
            //图片在线管理
            case 'listfile':
            case 'listimage':
                $listArr = $this->att_not_used();
                $list = array();
                foreach ($listArr as $rs) {
                    if (!AttachmentModel::model()->isImage($rs['src']) && $action != 'listfile') {
                        continue;
                    }
                    $list[] = array(
                        'url' => $rs['src'],
                        'mtime' => time(),
                    );
                }
                $result = array(
                    'state' => 'SUCCESS',
                    'list' => $list,
                    'total' => count($listArr),
                );
                break;
            //上传视频
            case 'uploadvideo':
            //上传附件
            case 'uploadfile':
                $Attachment = UploadFile::getInstance();
                //设置上传类型，强制为图片类型
                $Attachment->allowExts = array("jpg", "png", "gif", "jpeg", "zip", "7z", "rar");
                //开始上传
                $status = $Attachment->upload();
                if ($status) {
                    $info = $Attachment->getUploadFileInfo();
                    $url = ConfigModel::model()->getConfig('sitefileurl') . $info[0]['savepath'] . $info[0]['savename'];
                    // 设置附件cookie
                    AttachmentModel::model()->upload_json($info[0]['aid'], $url, str_replace(array("\\", "/"), "", $info[0]['name']));
                    $result = array(
                        'state' => 'SUCCESS', //成功返回标准，否则是错误提示
                        'url' => $url, //成功地址
                        'name' => str_replace(array("\\", "/"), "", $info[0]['name']), //上传后的文件名
                        'size' => $info[0]['size'],
                        'type' => '.' . $info[0]['extension'],
                        'original' => $info[0]['name'], //原来的
                    );
                } else {
                    $result = array(
                        'state' => $Attachment->getError()? : '上传失败'
                    );
                }
                break;
            default:
                $result = array(
                    'state' => '请求地址出错'
                );
                break;
        }
        exit(json_encode($result));
    }

    /**
     * 获取临时未处理的图片
     * @return type
     */
    protected function att_not_used() {
        //获取临时未处理文件列表
        $cookie = Yii::app()->request->getCookies();
        $att_json = Input::getVar($cookie['att_json']);
        if ($att_json) {
            if ($att_json) {
                $att_cookie_arr = explode('||', $att_json);
            }
            foreach ($att_cookie_arr as $_att_c)
                $att[] = json_decode($_att_c, true);
            if (is_array($att) && !empty($att)) {
                foreach ($att as $n => $v) {
                    $ext = AttachmentModel::model()->fileext($v['src']);
                    if (in_array($ext, array('jpg', 'gif', 'png', 'bmp', 'jpeg'))) {
                        $att[$n]['fileimg'] = $v['src'];
                        $att[$n]['width'] = '80';
                        $att[$n]['filename'] = urldecode($v['filename']);
                    } else {
                        $att[$n]['fileimg'] = AttachmentModel::model()->file_icon($v['src']);
                        $att[$n]['width'] = '64';
                        $att[$n]['filename'] = urldecode($v['filename']);
                    }
                }
            }
        }
        return $att;
    }

}
